                  
#include "ADS126x.h"
#include "stm32f4xx.h"
#include "assert.h"
#include "math.h"
#include "delay.h"

 //ADC所用到的命令控制字
#define COMM_RESET        0X06                        //复位
#define COMM_START        0X08                        //开始采样
#define COMM_STOP         0X0A                        //停止
#define COMM_READ_DATA    0X12                        //读取数据
#define COMM_SFOCAL1      0X19                        //
#define COMM_READ_REG     0X20                        //读寄存器
#define COMM_WRITE_REG    0X40                        //写寄存器
#define Average_NUMBER  	3
#define INVALID_COMMAND  	0

    unsigned long int AdcOutput0_1[2];      //温度测量通道1
    unsigned long int AdcOutput2_3[2];      //温度测量通道2
    unsigned long int AdcOutput8_9;         //压力测量通道
    unsigned long int AdcOutput0_1P[20];    //温度测量通道1正采样值暂存数组
    unsigned long int AdcOutput2_3P[20];    //温度测量通道2正采样值暂存数组
    unsigned long int AdcOutput0_1N[20];    //温度测量通道1反采样值暂存数组
    unsigned long int AdcOutput2_3N[20];    //温度测量通道2反采样值暂存数组
    unsigned long int AdcOutput8_9N[20];    //压力测量通道采样值暂存数组
	long int sum[2]={0,0};                  //采样和
	long int AveCH0_1;                      //滑动后通道1的采样平均值
    long int AveCH2_3;                      //滑动后通道2的采样平均值
    long int AveCH8_9;                      //滑动后压力通道采样平均值
	double R_average1 ;//电阻滑动平均值
	float TemUploadFloat;       //上传的浮点数温度
	double PreU;                            //电压计算值
    double Pres;                            //压力计算值
	int a=0,b=0,c=0,dd=0;
    long int value_buff[4][5];              //滑动平均时所用数组
    long int value[2][5];                   //滑动平均时所用数组
	long int kmax[2];                       //滑动时数组中的最大值
    long int kmin[2];                       //滑动时数组中的最小值
	long int Ave_Data_AIN01[2] = {0,0};     //温度测量通道1的平均值
    long int Ave_Data_AIN23[2] = {0,0};     //温度测量通道2的平均值
	int Ch0_state,Ch1_state,Ch2_state,Ch3_state,Ch4_state;  //采样数据插入数组中时所用变量
	long int AIN8_9[5];     //压力滑动平均时所用数组
	
//--------------------------------------------------------
void DelaySCLK(int u)
{
    int i;
    for (i = 0; i < u; i++);
}

void SCK (int status)
{
    if (status == 0)           GPIO_ResetBits(GPIOB,GPIO_Pin_13);     // PB13 = 0
    else if (status == 1)      GPIO_SetBits(GPIOB,GPIO_Pin_13);      // PB13 = 1
    delay_us(20);
}

void DIN (int status)
{
    if (status == 0)           GPIO_ResetBits(GPIOB,GPIO_Pin_15);     // PB15 = 0
    else if (status == 1)      GPIO_SetBits(GPIOB,GPIO_Pin_15);      // PB15 = 1
    delay_us(20);
}

void CS (int status)
{
    if (status == 0)           GPIO_ResetBits(GPIOD,GPIO_Pin_13);     // PD13 = 0
    else if (status == 1)      GPIO_SetBits(GPIOD,GPIO_Pin_13);      // PD13 = 1
    delay_us(20);
}

// 先发高位
void Send8Bit(int _data)
{
    int i;
    SCK(0);
    for(i = 0; i < 8; i++)
    {
        SCK(1);
        if (_data & 0x80) DIN(1);
        else DIN(0);
        _data <<= 1;
        SCK(0);
    }
}

// 先读高位
long int Recive(void)
{
    int i;
    long int read = 0;

    for (i = 0; i < 8; i++)
    {
        SCK(1);
        read = read<<1;
        if (GPIO_ReadInputDataBit(GPIOG,4) == 0)  read++;
        delay_us(10);
        SCK(0);
    }
        SCK(0);
    return read;
}	
	
	
	
//--------------------------------------------------------



	
	
 /**
 * @brief SPI_ADS126x 初始化
 * @param 无
 * @retval 无
 */
 void SPI_ADS126x_Init(void)
 {
 GPIO_InitTypeDef GPIO_InitStructure;
 
 /* 使能 ADS126x_SPI 及 GPIO 时钟 */
 /*!< SPI_ADS126x_SPI_CS_GPIO, SPI_ADS126x_SPI_MOSI_GPIO,
 SPI_ADS126x_SPI_MISO_GPIO 和 SPI_ADS126x_SPI_SCK_GPIO 时钟使能 */
 RCC_AHB1PeriphClockCmd (ADS126x_SPI_SCK_GPIO_CLK | ADS126x_SPI_MISO_GPIO_CLK|
 ADS126x_SPI_MOSI_GPIO_CLK|ADS126x_CS_GPIO_CLK, ENABLE);
 
 /*!< SPI_ADS126x_SPI 时钟使能 */
 ADS126x_SPI_CLK_INIT(ADS126x_SPI_CLK, ENABLE);
 
 //设置引脚复用
 GPIO_PinAFConfig(ADS126x_SPI_SCK_GPIO_PORT,ADS126x_SPI_SCK_PINSOURCE,
 ADS126x_SPI_SCK_AF);
 GPIO_PinAFConfig(ADS126x_SPI_MISO_GPIO_PORT,ADS126x_SPI_MISO_PINSOURCE,
 ADS126x_SPI_MISO_AF);
 GPIO_PinAFConfig(ADS126x_SPI_MOSI_GPIO_PORT,ADS126x_SPI_MOSI_PINSOURCE,
 ADS126x_SPI_MOSI_AF);
 
 /*!< 配置 SPI_ADS126x_SPI 引脚: SCK */
 GPIO_InitStructure.GPIO_Pin = ADS126x_SPI_SCK_PIN;
 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
 GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
 GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
 
 GPIO_Init(ADS126x_SPI_SCK_GPIO_PORT, &GPIO_InitStructure);
 
 /*!< 配置 SPI_ADS126x_SPI 引脚: MISO */
 GPIO_InitStructure.GPIO_Pin = ADS126x_SPI_MISO_PIN;
 GPIO_Init(ADS126x_SPI_MISO_GPIO_PORT, &GPIO_InitStructure);
 
 /*!< 配置 SPI_ADS126x_SPI 引脚: MOSI */
 GPIO_InitStructure.GPIO_Pin = ADS126x_SPI_MOSI_PIN;
 GPIO_Init(ADS126x_SPI_MOSI_GPIO_PORT, &GPIO_InitStructure);
 
 /*!< 配置 SPI_ADS126x_SPI 引脚: CS */
 GPIO_InitStructure.GPIO_Pin = ADS126x_CS_PIN;
 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
 GPIO_Init(ADS126x_CS_GPIO_PORT, &GPIO_InitStructure);
 
 /* 停止信号 ADS126x: CS 引脚高电平*/
 SPI_ADS126x_CS_HIGH(); 
 
 SPI_InitTypeDef SPI_InitStructure;
 /* ADS126x_SPI 模式配置 */
 // ADS126x 芯片 支持 SPI 模式 0 及模式 3，据此设置 CPOL CPHA  ---目前配置为模式3，但不确定使用哪个模式????
 SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
 SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
 SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
 SPI_InitStructure.SPI_CPOL = SPI_CPOL_High;
 SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;
 SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
 SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_2;
 SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
 SPI_InitStructure.SPI_CRCPolynomial = 7;
 SPI_Init(ADS126x_SPI, &SPI_InitStructure);
 
 /* 使能 ADS126x_SPI */
 SPI_Cmd(ADS126x_SPI, ENABLE);

 }
 
 #define Dummy_Byte 0xFF
 /**
 * @brief 使用 SPI 发送一个字节的数据
 * @param byte：要发送的数据
 * @retval 返回接收到的数据
 */
unsigned char ADS126x_SPI_WriteReadByte(unsigned char TxData)
{
	while (SPI_I2S_GetFlagStatus(ADS126x_SPI, SPI_I2S_FLAG_TXE) == RESET);//等待发送区空
	//while (SPI_I2S_GetFlagStatus(ADS126x_SPI, SPI_I2S_FLAG_BSY) == SET);	 
	SPI_I2S_SendData(ADS126x_SPI, TxData); //通过外设 SPIx 发送一个 byte 数据

	//while (SPI_I2S_GetFlagStatus(ADS126x_SPI, SPI_I2S_FLAG_BSY) == SET);
	while (SPI_I2S_GetFlagStatus(ADS126x_SPI, SPI_I2S_FLAG_RXNE) == RESET); //等待接收完
	return SPI_I2S_ReceiveData(ADS126x_SPI); //返回通过 SPIx 最近接收的数据
}
 
void ADS126x_SendResetCommand(void)
{
	/*
	SPI_ADS126x_CS_LOW();
    ADS126x_SPI_WriteReadByte(COMM_RESET);
    SPI_ADS126x_CS_HIGH();
	*/
	CS(0);
    Send8Bit(COMM_RESET);
    CS(1);
	
}
void ADS126x_SendStartCommand(void)
{
	/*
	SPI_ADS126x_CS_LOW();
    ADS126x_SPI_WriteReadByte(COMM_START);
    SPI_ADS126x_CS_HIGH();
	*/
	CS(0);
    Send8Bit(COMM_START);
    CS(1);
}
void ADS126x_SendStopCommand(void)
{
	/*
	SPI_ADS126x_CS_LOW();
    ADS126x_SPI_WriteReadByte(COMM_STOP);
    SPI_ADS126x_CS_HIGH();
	*/
	CS(0);
    Send8Bit(COMM_STOP);
    CS(1);
}
void ADS126xWriteRegister(int StartAddress, int NumRegs, unsigned char * pdata)
{
/* --------------------------------------------
	SPI_ADS126x_CS_LOW();
    ADS126x_SPI_WriteReadByte(0x40+StartAddress);
    ADS126x_SPI_WriteReadByte(NumRegs-1);
	int i;
    for(i=0;i<NumRegs;i++)
    ADS126x_SPI_WriteReadByte(pdata[i]);
    SPI_ADS126x_CS_HIGH();
-----------------------------------------------*/ 
	CS(0);// --使片选信号（CS）为低电平，开始通信
    Send8Bit(0x40+StartAddress);// --发送写寄存器的命令和寄存器起始地址
    Send8Bit(NumRegs-1);// --发送要写入的寄存器数量（减1是因为通常是从起始地址写入连续的多个寄存器）
    for(int i=0;i<NumRegs;i++)// --循环发送要写入的数据
    Send8Bit(pdata[i]);
    CS(1); // --结束通信，使片选信号恢复高电平
}

//----
void ADS126xReadRegister(int StartAddress, int NumRegs, unsigned char *pdata)//--读取寄存器的值
{
	/*
    SPI_ADS126x_CS_LOW(); // --使片选信号（CS）为低电平，开始通信
    ADS126x_SPI_WriteReadByte(0x20 + StartAddress);// --发送读寄存器的命令和寄存器起始地址
    ADS126x_SPI_WriteReadByte(NumRegs - 1);// --发送要读取的寄存器数量（减1是因为通常是从起始地址读取连续的多个寄存器）
    for(int i=0;i<NumRegs;i++)// --循环接收要读取的数据
    {
        pdata[i] = ADS126x_SPI_WriteReadByte(Dummy_Byte);// --接收一个字节的数据 //--先读高位
    }
    SPI_ADS126x_CS_HIGH();// --结束通信，使片选信号恢复高电平
	*/
	CS(0); // --使片选信号（CS）为低电平，开始通信
    Send8Bit(0x20 + StartAddress);// --发送读寄存器的命令和寄存器起始地址
    Send8Bit(NumRegs - 1);// --发送要读取的寄存器数量（减1是因为通常是从起始地址读取连续的多个寄存器）
    for(int i=0;i<NumRegs;i++)// --循环接收要读取的数据
    {
        pdata[i] = Recive();// --接收一个字节的数据
    }
    CS(1);// --结束通信，使片选信号恢复高电平
}
//---

    int status;             //ADC状态变量
    int crc;                //ADC状态变量
	int initOver=0;         //ADC测试用变量，进入ADC初始化函数后会变成1
    volatile unsigned int q;
    int i;
    int l;
    int j;
    int fre;                    //频率测量次数
    unsigned char result;       //滑动平均后的暂存变量
    unsigned char ainx;         //ADC采样通道设置变量
    unsigned char modx;         //ADC采样通道极性设置变量
    unsigned char pgax;         //ADC采样率设置变量
    unsigned char filx;         //ADC滤波设置变量
    int PO1,PO2,NE1,NE2,Pr3;    //观察采样值所用变量
void ADS126x_Init(void)
{
    unsigned char temp;
    initOver = 1;
    temp = 0x11;                            // 复位，偏置关闭，内部参考关闭
    ADS126xWriteRegister(POWER, 1, &temp);

    temp = 0x05;                            // 关闭串口超时，使能状态字节和校验
    ADS126xWriteRegister(INTERFACE, 1, &temp);
    //AIN0:AIN3
    //ainx = 0x1B;                            // 选择AIN4-AIN5作为外部参考源输入的正负引脚_00011011
    //ADS126xWriteRegister(REFMUX, 1, &ainx);
    //ainx = 0x01;
    //ADS126xWriteRegister(0x06, 1, &ainx);   // 选择AIN0-AIN1作为电压输入的正负引脚
    //MODEx 正常的参考电压极性，连续转换模式，斩波使能，转换278us延时;sinC4模式
    modx = 0x16;
    ADS126xWriteRegister(MODE0, 1, &modx);
    filx = 0x60;
    ADS126xWriteRegister(MODE1, 1, &filx);
    //PGA 1; Data Rate 2.5 SPS
    pgax = GAIN_1 | DR_50_SPS;                  //设置采样率
    ADS126xWriteRegister(MODE2, 1, &pgax);
}
void ADS126x_Reset(void)//--通过发送复位命令，等待一定时间，然后执行初始化操作，将 ADS126x 模数转换器带回到一个可用状态。
{
        ADS126x_SendResetCommand();
		delay_us(10);
        ADS126x_Init();
}
//--
//void my_assert(int expression) 
//{
//    if (!expression) 
//	{
//        abort();
//    }
//}
//--

long int ADS126xReadData(int NumBytes, int DataByteStartNum)
{
	/*
    int  ADC_Bytes[6];                                                   //Holds
    long int  ADC_Data_Only;

    SPI_ADS126x_CS_LOW();
	
//--
//    // 使用自定义的 my_assert 函数替代 assert 宏
//	my_assert((4 == NumBytes) || (5 == NumBytes) || (6 == NumBytes));
//    my_assert((0 == DataByteStartNum) || (1 == DataByteStartNum));
//--

    for(i = 0; i < NumBytes; i++)
        ADC_Bytes[i] = ADS126x_SPI_WriteReadByte(Dummy_Byte);

    status = (ADC_Bytes[0] << 0);                                            // if enable status
    ADC_Data_Only = ((long int)ADC_Bytes[DataByteStartNum + 0] << 24) |      // Data MSB
                    ((long int)ADC_Bytes[DataByteStartNum + 1] << 16) |
                    ((long int)ADC_Bytes[DataByteStartNum + 2] <<  8) |
                    ((long int)ADC_Bytes[DataByteStartNum + 3] <<  0);       // Data LSB
    crc =  (ADC_Bytes[DataByteStartNum + 4] << 0);                           // if enable crc
    SPI_ADS126x_CS_HIGH();

    return ADC_Data_Only;
	*/
	int  ADC_Bytes[6];        // --存储从模数转换器读取的字节                                           //Holds
    long int  ADC_Data_Only;  // --存储仅包含数据的结果

    CS(0);

    for(i = 0; i < NumBytes; i++)
        ADC_Bytes[i] = Recive(); // --读取指定数量的字节数据

    status = (ADC_Bytes[0] << 0);   // --从读取的字节中提取状态信息                                         // if enable status
    ADC_Data_Only = ((long int)ADC_Bytes[DataByteStartNum + 0] << 24) |      // Data MSB  // --从读取的字节中提取数据
                    ((long int)ADC_Bytes[DataByteStartNum + 1] << 16) |
                    ((long int)ADC_Bytes[DataByteStartNum + 2] <<  8) |
                    ((long int)ADC_Bytes[DataByteStartNum + 3] <<  0);       // Data LSB
    crc =  (ADC_Bytes[DataByteStartNum + 4] << 0);    // --从读取的字节中提取 CRC 校验值                       // if enable crc
    CS(1);

    return ADC_Data_Only; // --返回仅包含数据的结果
}

//温度校正函数
double P_rtdToTemperature(const double dRaw)
{
    double dTemp;

    double a0 = 0.00305139026052568;
    double a1 = 0.000743998478386825;
    double a2 = -0.000790418616368492;
    double a3 = 0.000399867424635872;

    dTemp = 1/(a0 + a1*log(dRaw) + a2*log(dRaw)*log(dRaw) + a3*log(dRaw)*log(dRaw)*log(dRaw))-273.15;
    return dTemp;
}

long int filter(int state)
{
    int count;
    int k,m;
    int flag;
   if (state==0)
    {
    value_buff[0][a++]=AdcOutput0_1[state];
    value_buff[1][b++]=AdcOutput2_3[state];
    for(flag=0;flag<5;flag++)
    {value[0][flag]=value_buff[0][flag];
     value[1][flag]=value_buff[1][flag];
    }

    }
   else
    {
      value_buff[2][c++]=AdcOutput0_1[state];
      value_buff[3][dd++]=AdcOutput2_3[state];
        for(flag=0;flag<5;flag++)
        {
        value[0][flag]=value_buff[2][flag];
        value[1][flag]=value_buff[3][flag];
        }
    }

    if(a==5)
        a=0;
    if(b==5)
        b=0;
    if(c==5)
        c=0;
    if(dd==5)
        dd=0;
    for(m=0;m<2;m++)
    {
    kmax[m]=kmin[m]=value[m][0];
    for (k=1;k<5;k++)
    {
        if(value[m][k]>kmax[m])
        {
            kmax[m]=value[m][k];
        }
        if(value[m][k]<kmin[m])
        {
            kmin[m]=value[m][k];
        }
    }
    }
        for(count=0;count<5;count++)
        {
        sum[0]+=value[0][count];
        sum[1]+=value[1][count];

        }
        Ave_Data_AIN01[state]=(sum[0]-kmax[0]-kmin[0])/3;
        Ave_Data_AIN23[state]=(sum[1]-kmax[1]-kmin[1])/3;

    return 0;

}

//将采样数据插入数组中
void InsertNumber (long int adArray[Average_NUMBER],long int Result,int state)
{
    switch(state)
    {
    case 0:
        adArray[Ch0_state]=Result;
        (Ch0_state<(Average_NUMBER-1))? (Ch0_state++):(Ch0_state=0);
        break;
    case 1:
        adArray[Ch1_state]=Result;
        (Ch1_state<(Average_NUMBER-1))? (Ch1_state++):(Ch1_state=0);
        break;
    case 2:
        adArray[Ch2_state]=Result;
        (Ch2_state<(Average_NUMBER-1))? (Ch2_state++):(Ch2_state=0);
        break;
    case 3:
        adArray[Ch3_state]=Result;
        (Ch3_state<(Average_NUMBER-1))? (Ch3_state++):(Ch3_state=0);
        break;
    case 4:
        adArray[Ch4_state]=Result;
        (Ch4_state<(Average_NUMBER-1))? (Ch4_state++):(Ch4_state=0);
        break;
    }

}

/************************************************************
滑动平均
************************************************************
*/
unsigned long int GetAveraging(long int adarray[Average_NUMBER])
{
    unsigned long long int dResult = 0;
    int m,i;
    long int alternate[2];
    alternate[0]=adarray[0];
    alternate[1]=adarray[0];
    for(m=0; m<Average_NUMBER; m++)
    {
        if(alternate[0]<adarray[m])
            alternate[0]=adarray[m];
        if(alternate[1]>adarray[m])
            alternate[1]=adarray[m];
    }
    for (i=0; i<Average_NUMBER; i++)
    {
        dResult += adarray[i];
    }
    dResult=dResult-alternate[1]-alternate[0];
#ifdef __DEBUG__
    return (dResult/(Average_NUMBER-2));
#endif

    return (dResult/(Average_NUMBER-2));

}

/***********************************
 * 压力的滑动平均
 * 入口：压力的测量结果
 * 出口：滑动平均后的值
 * *********************************/
long int smooth (long int x)
{
    unsigned long int result;
    InsertNumber(AIN8_9,AdcOutput8_9,4);
    result = GetAveraging(AIN8_9);
    return result;
}

//压力温度校正函数
double Pressure(double preU)
{
    double Pres;

    double p0 = -4.406;
    double p1 = 620;
    double p2 = -1.83;
    double p3 = 1.527;
    double p4 = -0.6964;

    Pres = p0+p1*PreU+p2*PreU*PreU+p3*PreU*PreU*PreU+p4*PreU*PreU*PreU*PreU;
    return Pres;
}



void Temperature (void)
{
	R_average1=0; //--???
    ADS126x_Reset();                         //ADC复位
////温度
// Y=0
    GPIO_ResetBits(GPIOD,9);
    ainx = 0x01;
    ADS126xWriteRegister(INPMUX, 1, &ainx);   // 选择AIN0-AIN1作为电压输入的正负引脚
    ADS126x_SendStartCommand();   //用命令启动转换时，将START引脚拉低，避免冲突
    while(GPIO_ReadInputDataBit(GPIOG,4) == 0);
    AdcOutput0_1[0] = ADS126xReadData(6, 1);
    AdcOutput0_1P[PO1++] = AdcOutput0_1[0];    //观察用
    if(PO1 == 20)    PO1 = 0;                  //

    ainx = 0x23;
    ADS126xWriteRegister(INPMUX, 1, &ainx);   // 选择AIN0-AIN1作为电压输入的正负引脚
    ADS126x_SendStartCommand();   //用命令启动转换时，将START引脚拉低，避免冲突
    while(GPIO_ReadInputDataBit(GPIOG,4) == 0);
    AdcOutput2_3[0] = ADS126xReadData(6, 1);
    AdcOutput2_3P[PO2++] = AdcOutput2_3[0];     //观察用
    if(PO2 == 20)    PO2 = 0;
    sum[0]=0;
    sum[1]=0;
    filter(0);
// Y = 1
    GPIO_SetBits(GPIOD,9);
    ainx = 0x10;
    ADS126xWriteRegister(INPMUX, 1, &ainx);   // 选择AIN0-AIN1作为电压输入的正负引脚
    ADS126x_SendStartCommand();   //用命令启动转换时，将START引脚拉低，避免冲突
    while(GPIO_ReadInputDataBit(GPIOG,4) == 0);
    AdcOutput0_1[1] = ADS126xReadData(6, 1);
    AdcOutput0_1N[NE1++] = AdcOutput0_1[1];     //观察用
    if(NE1 == 20)    NE1 = 0;

    ainx = 0x32;
    ADS126xWriteRegister(INPMUX, 1, &ainx);   // 选择AIN0-AIN1作为电压输入的正负引脚
    ADS126x_SendStartCommand();   //用命令启动转换时，将START引脚拉低，避免冲突
    while(GPIO_ReadInputDataBit(GPIOD,4) == 0);
    AdcOutput2_3[1] = ADS126xReadData(6, 1);    //观察用
    AdcOutput2_3N[NE2++] = AdcOutput2_3[1];
    if(NE2== 20)    NE2 = 0;
    sum[0]=0;
    sum[1]=0;
    filter(1);
/***********压力***********/
// Y=0
    GPIO_ResetBits(GPIOD,9);
    ainx = 0x89;
    ADS126xWriteRegister(INPMUX, 1, &ainx);   // 选择AIN8-AIN9作为电压输入的正负引脚
    ADS126x_SendStartCommand();   //用命令启动转换时，将START引脚拉低，避免冲突
    while(GPIO_ReadInputDataBit(GPIOG,4) == 0);
    AdcOutput8_9 = ADS126xReadData(6, 1);
    AdcOutput8_9N[Pr3++] = AdcOutput8_9;
    if(Pr3 == 20)    Pr3 = 0;
    AveCH8_9 = smooth(AdcOutput8_9);//压力滑动平均

    AveCH0_1 = (AdcOutput0_1[0] + AdcOutput0_1[1]) >>1; //相加除2求平均
    AveCH2_3 = (AdcOutput2_3[0] + AdcOutput2_3[1]) >>1; //相加除2求平均

    R_average1 = 10.0807 * AveCH2_3 / AveCH0_1;
    TemUploadFloat = P_rtdToTemperature(R_average1);     //计算温度值

    PreU = 2.5 * AdcOutput8_9 / 0x80000000;
    Pres = Pressure(PreU);

}

/***********************************
 * 电导率的滑动平均
 * 入口：频率的测量结果x
 * 出口：频率滑动平均后的值result
 * *********************************/
double Csmooth (double x) //--这个函数使用了一个长度为30的环形缓冲区 Csmooth_data，并在每次调用时将输入数据 x 插入到缓冲区中。
{                         //--然后，通过遍历缓冲区，计算数据的和以及最大值和最小值。
                          //--最终，通过去除最大值和最小值，计算平均值，并将平滑处理后的结果返回。
    int j = 0;
    double datamax,datamin;

    double databuff[30];
    double datasum = 0;
    double result;
	
	double Csmooth_data[5];                 //频率滤波数组
    int Csmooth_i = 0;                      //滤波计数值

    Csmooth_data[Csmooth_i++] = x;
    if(Csmooth_i == 30) // --循环使用缓冲区
        Csmooth_i = 0;

    datamax = datamin = Csmooth_data[0];

    for(j=0;j<30;j++)// --遍历缓冲区，计算数据的和以及最大值和最小值
    {
        datasum += Csmooth_data[j];
        databuff[j] = Csmooth_data[j];

        if(databuff[j]>datamax)
            datamax = databuff[j];
        if(databuff[j]<datamin)
            datamin = databuff[j];
    }
    result = (datasum - datamax - datamin)/28;// --计算平均值，去除最大值和最小值

    return result;
}

/***********************************
 * 中位数滤波（最后没用到）
 * 入口：测量结果x
 * 出口：value_buff
 * *********************************/
double middlevalueFilter (double x)
{
    double value_buff[5];
    int mi,mj,mk;
    double temp;

    for(mi=0;mi<5;mi++)
    {
        value_buff[mi] = x;
    }
    for(mj=0;mj<5;mj++)
    {
        for(mk=0;mk<5-mj;mk++)
        {
            if(value_buff[mk]>value_buff[mk+1])
            {
                temp = value_buff[mk];
                value_buff[mk] = value_buff[mk+1];
                value_buff[mk+1] = temp;
            }
        }
    }

    return value_buff[2];
}
void TIM2_Init(void) {
    // 使能 TIM2 时钟
    RCC->APB1ENR |= RCC_APB1ENR_TIM2EN;

    // 设置预分频器值
    TIM2->PSC = 0;

    // 启用捕获/比较通道1
    TIM2->CCMR1 |= TIM_CCMR1_CC1S_0;

    // 启用更新中断
    TIM2->DIER |= TIM_DIER_CC1IE;

    // 启用 TIM2
    TIM2->CR1 |= TIM_CR1_CEN;

    // 设置中断优先级
    NVIC_SetPriority(TIM2_IRQn, 0);
    NVIC_EnableIRQ(TIM2_IRQn);
}

//电导率校正函数
unsigned long int tval[2] = {0};
unsigned long int count_c[2] = {0};

extern double f;                               //电导率分频后频率
extern int fre;                    //频率测量次数
extern float FreUploadFloat;       //上传的浮点数频率
extern double G;                   //电导率值
extern double ConUploadFloat;       //上传的浮点数电导率
extern double fr;                              //电导率分频前频率


//void Conductivity (void) //--这段代码使用计时器B（Timer B）来测量时间，并通过一系列的计算和处理步骤（包括调用 Csmooth 函数、进行一些数学运算等）来计算电导率（Conductivity）。
//{                        //--其中，FreUploadFloat 和 ConUploadFloat 变量可能用于存储计算得到的频率和电导率值。
////                         //--这段代码执行了30次循环，每次循环测量一次电导率。

//    unsigned int count = 0;
//    while(count<30)
//  {
//    unsigned int flag = 1;
//    while (flag < 3)//频率计算
//    {
//        if ((TIM2->SR & TIM_SR_CC1IF) != 0)         //开启捕获中断
//        {
//            if(flag == 1)
//            {
//                //TBR = 0
//				tval[0] = TIM2->CCR1;
//                count_c[0] = TIM2->CCR1;
//            }
//            else if(flag == 2)
//            {
//                tval[1] = TIM2->CCR1;
//                f = 14745600.0 / (tval[1] - tval[0] + 65536* count_c[1]);
//                fr = (0.0055*f) / 83.000;
//                f=fr+f;

//                fr = Csmooth (f);
//                FreUploadFloat = fr;
//                fr = fr * 32;
//                G = fr / 1000;
//                ConUploadFloat = 6.13354567028508-4.06468223915935*G+2.16278309337694*G*log(G)-7.1551351900011/(G*G);
//                count_c[1]=0;
//                count_c[0]=0;
//            }
//            flag++;
//            TIM2->SR &= ~TIM_SR_CC1IF;
//        }
////        if (flag<3)//计数值计算
////           {
////           while((TBCCTL0 & CCIFG) == 0)
////                  {
////                       if(count_c[0]>=(TBR+1))
////                      {
////                          count_c[1]++;
////                          count_c[0] = TBR;//实时计数器的计数值
////                      }
////                  }
////           }
//		    if (flag < 3) {
//            while ((TIM2->SR & TIM_SR_CC1IF) == 0);
//            while ((TIM2->CCR1 - count_c[0]) < (TIM2->CNT + 1));
//        }
//		delay_ms(10);
//    }
//    ++count;
//   }
//    //_EINT();	


//}

